using Microsoft.EntityFrameworkCore;
using WeatherApp.Models;

namespace WeatherApp.Services
{
    public class DataService : IDataService
    {
        private readonly WeatherDbContext _context;
        private readonly ILogger<DataService> _logger;

        public DataService(WeatherDbContext context, ILogger<DataService> logger)
        {
            _context = context;
            _logger = logger;
        }

        #region 天气记录相关

        public async Task<WeatherRecord> SaveWeatherRecordAsync(WeatherInfo weatherInfo)
        {
            try
            {
                var record = new WeatherRecord
                {
                    City = weatherInfo.City,
                    Weather = weatherInfo.Weather,
                    Temperature = weatherInfo.Temperature,
                    Humidity = weatherInfo.Humidity,
                    WindDirection = weatherInfo.WindDirection,
                    WindPower = weatherInfo.WindPower,
                    AirQuality = weatherInfo.AirQuality,
                    UvIndex = weatherInfo.UvIndex,
                    Visibility = weatherInfo.Visibility,
                    Pressure = weatherInfo.Pressure,
                    FeelsLike = weatherInfo.FeelsLike,
                    QueryTime = DateTime.Now
                };

                _context.WeatherRecords.Add(record);
                await _context.SaveChangesAsync();

                _logger.LogInformation("保存天气记录成功: {City}", weatherInfo.City);
                return record;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存天气记录失败: {City}", weatherInfo.City);
                throw;
            }
        }

        public async Task<List<WeatherRecord>> GetWeatherHistoryAsync(string city, int days = 7)
        {
            try
            {
                var startDate = DateTime.Now.AddDays(-days);
                var records = await _context.WeatherRecords
                    .Where(r => r.City == city && r.QueryTime >= startDate)
                    .OrderByDescending(r => r.QueryTime)
                    .ToListAsync();

                return records;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取天气历史失败: {City}", city);
                return new List<WeatherRecord>();
            }
        }

        public async Task<List<WeatherRecord>> GetRecentWeatherRecordsAsync(int count = 10)
        {
            try
            {
                var records = await _context.WeatherRecords
                    .OrderByDescending(r => r.QueryTime)
                    .Take(count)
                    .ToListAsync();

                return records;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取最近天气记录失败");
                return new List<WeatherRecord>();
            }
        }

        #endregion

        #region 用户设置相关

        public async Task<UserSettings> GetUserSettingsAsync(string userId)
        {
            try
            {
                var settings = await _context.UserSettings
                    .FirstOrDefaultAsync(u => u.UserId == userId);

                if (settings == null)
                {
                    // 创建默认设置
                    settings = new UserSettings
                    {
                        UserId = userId,
                        TemperatureUnit = "Celsius",
                        Language = "zh-CN",
                        Theme = "light",
                        Notifications = true
                    };

                    _context.UserSettings.Add(settings);
                    await _context.SaveChangesAsync();
                }

                // 加载收藏城市和搜索历史
                await LoadUserRelatedDataAsync(settings);

                return settings;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户设置失败: {UserId}", userId);
                throw;
            }
        }

        public async Task<UserSettings> SaveUserSettingsAsync(string userId, UserSettingsDto settingsDto)
        {
            try
            {
                var settings = await _context.UserSettings
                    .FirstOrDefaultAsync(u => u.UserId == userId);

                if (settings == null)
                {
                    settings = new UserSettings
                    {
                        UserId = userId
                    };
                    _context.UserSettings.Add(settings);
                }

                // 更新设置
                settings.TemperatureUnit = settingsDto.TemperatureUnit;
                settings.Language = settingsDto.Language;
                settings.Theme = settingsDto.Theme;
                settings.Notifications = settingsDto.Notifications;

                await _context.SaveChangesAsync();

                // 加载相关数据
                await LoadUserRelatedDataAsync(settings);

                return settings;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存用户设置失败: {UserId}", userId);
                throw;
            }
        }

        public async Task<bool> DeleteUserSettingsAsync(string userId)
        {
            try
            {
                var settings = await _context.UserSettings
                    .FirstOrDefaultAsync(u => u.UserId == userId);

                if (settings != null)
                {
                    _context.UserSettings.Remove(settings);
                    await _context.SaveChangesAsync();
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除用户设置失败: {UserId}", userId);
                return false;
            }
        }

        #endregion

        #region 搜索历史相关

        public async Task<List<SearchHistory>> GetSearchHistoryAsync(string userId, int count = 10)
        {
            try
            {
                var history = await _context.SearchHistories
                    .Where(h => h.UserId == userId)
                    .OrderByDescending(h => h.SearchTime)
                    .Take(count)
                    .ToListAsync();

                return history;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取搜索历史失败: {UserId}", userId);
                return new List<SearchHistory>();
            }
        }

        public async Task<SearchHistory> AddSearchHistoryAsync(string userId, string cityName)
        {
            try
            {
                // 删除已存在的相同记录
                var existing = await _context.SearchHistories
                    .FirstOrDefaultAsync(h => h.UserId == userId && h.CityName == cityName);

                if (existing != null)
                {
                    _context.SearchHistories.Remove(existing);
                }

                var history = new SearchHistory
                {
                    UserId = userId,
                    CityName = cityName,
                    SearchTime = DateTime.Now
                };

                _context.SearchHistories.Add(history);
                await _context.SaveChangesAsync();

                return history;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加搜索历史失败: {UserId}, {CityName}", userId, cityName);
                throw;
            }
        }

        public async Task<bool> ClearSearchHistoryAsync(string userId)
        {
            try
            {
                var histories = await _context.SearchHistories
                    .Where(h => h.UserId == userId)
                    .ToListAsync();

                _context.SearchHistories.RemoveRange(histories);
                await _context.SaveChangesAsync();

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清空搜索历史失败: {UserId}", userId);
                return false;
            }
        }

        #endregion

        #region 收藏城市相关

        public async Task<List<FavoriteCity>> GetFavoriteCitiesAsync(string userId)
        {
            try
            {
                var favorites = await _context.FavoriteCities
                    .Where(f => f.UserId == userId)
                    .OrderBy(f => f.AddTime)
                    .ToListAsync();

                return favorites;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取收藏城市失败: {UserId}", userId);
                return new List<FavoriteCity>();
            }
        }

        public async Task<FavoriteCity> AddFavoriteCityAsync(string userId, string cityName)
        {
            try
            {
                // 检查是否已存在
                var existing = await _context.FavoriteCities
                    .FirstOrDefaultAsync(f => f.UserId == userId && f.CityName == cityName);

                if (existing != null)
                {
                    return existing;
                }

                var favorite = new FavoriteCity
                {
                    UserId = userId,
                    CityName = cityName,
                    AddTime = DateTime.Now
                };

                _context.FavoriteCities.Add(favorite);
                await _context.SaveChangesAsync();

                return favorite;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加收藏城市失败: {UserId}, {CityName}", userId, cityName);
                throw;
            }
        }

        public async Task<bool> RemoveFavoriteCityAsync(string userId, string cityName)
        {
            try
            {
                var favorite = await _context.FavoriteCities
                    .FirstOrDefaultAsync(f => f.UserId == userId && f.CityName == cityName);

                if (favorite != null)
                {
                    _context.FavoriteCities.Remove(favorite);
                    await _context.SaveChangesAsync();
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "移除收藏城市失败: {UserId}, {CityName}", userId, cityName);
                return false;
            }
        }

        public async Task<bool> IsFavoriteCityAsync(string userId, string cityName)
        {
            try
            {
                return await _context.FavoriteCities
                    .AnyAsync(f => f.UserId == userId && f.CityName == cityName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查收藏城市失败: {UserId}, {CityName}", userId, cityName);
                return false;
            }
        }

        #endregion

        #region 私有方法

        private async Task LoadUserRelatedDataAsync(UserSettings settings)
        {
            try
            {
                // 加载收藏城市
                var favorites = await _context.FavoriteCities
                    .Where(f => f.UserId == settings.UserId)
                    .Select(f => f.CityName)
                    .ToListAsync();

                settings.FavoriteCities = favorites;

                // 加载搜索历史
                var history = await _context.SearchHistories
                    .Where(h => h.UserId == settings.UserId)
                    .OrderByDescending(h => h.SearchTime)
                    .Take(10)
                    .Select(h => h.CityName)
                    .ToListAsync();

                settings.SearchHistory = history;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载用户相关数据失败: {UserId}", settings.UserId);
            }
        }

        #endregion
    }
} 